import React from 'react'
import { Drawer, Button, Upload, Icon, message, Form } from 'antd'

class PictureDrawerForm extends React.Component {
    state = {
        id: '',
        ids: [],
        loading: false,
        visible: false,
        fileList: []
    }

    componentDidMount() {
        this.props.onRef(this)
    }

    beforeUpload = file => {
        const isType = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/bmp'
        const isLt10M = file.size / 1024 / 1024 < 10

        if (!isType) {
            message.info('仅支持.jpg、.jpeg、.bmp格式！')
            return isType
        }

        if (!isLt10M) {
            message.info('图片大小不能超过10MB！')
            return isLt10M
        }
    }

    handleChange = ({ file, fileList }) => {
        if (file.response && file.response.code !== 1) {
            message.info(file.response.data)
            fileList.length--
            this.setState({ fileList })
            return
        }

        if (!file.status) {
            fileList.length--
            this.setState({ fileList })
            return
        }

        if (file.response &&  file.status === 'done') {
            fileList[fileList.length - 1].url = file.response.data
        }

        this.setState({ fileList })
    }

    handleRemove = file => {
        if (file.id) this.state.ids.push(file.id)
    }

    // 获取详情
	getPicList = async id => {
        this.setState({ id })

        let { data } = await React.$axios.get(`/SchoolDisplay/GetSchoolDisplayDetailList?schoolDisplayId=${id}`)

        data.forEach((item, index) => {
            item.uid = '-' + (index + 1)
            item.url = item.picUrl
        })

        this.setState({
            fileList: data
        })

		this.toggleDrawer()
	}

    // 显示隐藏左侧弹窗
    toggleDrawer = () => {
        this.setState({
            visible: !this.state.visible
        })
    }

    // 获取文件url
    getUrl = url => {
        if (!url) return
        const newUrl = url.split('/').slice(-2).join('/')

        return '/' + newUrl
    }
    
    // 提交表单
    handleSubmit = async () => {
        this.setState({ loading: true })

        this.state.fileList = this.state.fileList.map((item, index) => {
            return {
                id: item.id || 0,
                uid: '-' + (index + 1),
                schoolDispayId: this.state.id,
                picUrl: this.getUrl(item.url)
            }
        })

        const formData = new FormData()
        formData.append('list', JSON.stringify(this.state.fileList))

        if (this.state.ids.length) await React.$axios.get(`/SchoolDisplay/DeleteSchoolDisplayDetail?id=${this.state.ids.join()}`)

        const { code, message: mes } = await React.$axios.post('/SchoolDisplay/AddSchoolDisplayDetail', formData)

        message.info(mes)

        this.setState({ 
            loading: false,
            ids: []
        })

        if (code === 1) this.toggleDrawer()
    }

    render() {
        const { fileList } = this.state

        return (
            <div>
                <Drawer
                    title={ '校区图片' }
                    width={ 360 }
                    onClose={ this.toggleDrawer }
                    visible={ this.state.visible }
                    bodyStyle={{ paddingBottom: 80 }}
                >
                    <Upload
                        action="api/UploadFile/UploadImg"
                        accept="image/bmp, image/jpeg, image/jpg"
                        headers={{ Authorization: localStorage.token }}
                        listType="picture-card"
                        fileList={ fileList }
                        beforeUpload={ this.beforeUpload }
                        onChange={ this.handleChange }
                        onRemove={ this.handleRemove }
                        >
                        <div>
                            <Icon type="plus" />
                            <div className="ant-upload-text">上传图片</div>
                        </div>
                    </Upload>
                    <p>仅支持.jpg、.jpeg、.bmp格式，大小10MB以内</p>
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={ this.toggleDrawer } style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button loading={ this.state.loading } onClick={ this.handleSubmit } type="primary">
                            确定
                        </Button>
                    </div>
                </Drawer>
            </div>
        )
    }
}

export default Form.create()(PictureDrawerForm)